package cn.iocoder.yudao.framework.websocket.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.Assert;

import java.util.Map;


@Slf4j
public class WebSocketChannelInterceptor implements ChannelInterceptor {

    /**
     * 客户端每次发送指令之前可以做的处理
     *
     */
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        //1、判断是否首次连接
        Assert.notNull(accessor,"websocket发生严重错误");
        Map<String, Object> sessionAttributes = accessor.getSessionAttributes();
        Assert.notNull(sessionAttributes,"sessionAttributes 不可能为空");
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            log.info("第一次连接");
        }
        else if(StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
            log.info(String.valueOf(accessor));
        }
        //不是首次连接，已经登陆成功
        return message;
    }

}
